
package tomcat;

import java.io.File;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

/**
 * @Title:
 *         <P>
 *         TomcatServer.java
 *         </P>
 * @Package
 *          <P>
 *          com.xs.tomcat
 *          </P>
 * @Description:
 *               <P>
 *               TODO该类...
 *               </P>
 * @author renweiping
 * @date 2019年1月14日 上午10:08:55
 * @version 1.0
 */

public class StartTomcat {

	/**
	 * @Description: TODO
	 * @param @param
	 *            args
	 * @return void
	 * @throws @author
	 *             renweiping
	 * @e_mail renweiping_1113@google.com
	 * @date 2019年1月14日
	 */
	//本地调试时
	public static void main2(String[] args) throws LifecycleException {

		String webappDirLocation = "src/main/webapp";
		System.out.println("webappDirLocation=" + new File(webappDirLocation).getAbsolutePath());
		Tomcat tomcat = new Tomcat();
		tomcat.setPort(9090);

		// 设置webapp路径 
		StandardContext ctx = (StandardContext) tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath());
		ctx.setReloadable(false);
		// 设置资源地址
		File additionWebInfClasses = new File("target/classes");
		WebResourceRoot resources = new StandardRoot(ctx);
		resources.addPreResources(
				new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));

		// 设置web xml
		ctx.setDefaultWebXml("src/main/webapp/WEB-INF/web.xml");

		// 设置servlet
		tomcat.addServlet("", "demoServelt", new TomcatServlet()).addMapping("/demo");

		tomcat.start();
		tomcat.getServer().await();

	}
	
	//打包时
	public static void main(String[] args) throws LifecycleException {

		String webappDirLocation = "webapp";
		System.out.println("webappDirLocation=" + new File(webappDirLocation).getAbsolutePath());
		Tomcat tomcat = new Tomcat();
		tomcat.setPort(9090);

		// 设置webapp路径 
		StandardContext ctx = (StandardContext) tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath());
		ctx.setReloadable(false);
		// 设置资源地址
		File additionWebInfClasses = new File("webapp/WEB-INF/classes");
		WebResourceRoot resources = new StandardRoot(ctx);
		resources.addPreResources(
				new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));

		// 设置web xml
		ctx.setDefaultWebXml("webapp/WEB-INF/web.xml");

		// 设置servlet
		tomcat.addServlet("", "demoServelt", new TomcatServlet()).addMapping("/demo");

		tomcat.start();
		tomcat.getServer().await();

	}
	

}
